package com.ruoyi.social.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.Apps.Utils.UrlConfigUtils;
import com.ruoyi.common.exception.I18nException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.social.view.RequestFullItem;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SocialProcessorService {

    @Value("${product.api.full}")
    private String productHost;

    @Value("${product.api.callback}")
    private String callbackUrl;


    public String getFullRequest(String url, String type, Long productId){
        String fullUrl = UrlConfigUtils.fullUrl.get(type);
        if (StringUtils.isEmpty(fullUrl)) {
            throw new I18nException("product.no.channel");
        }
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(productHost + fullUrl);
            JSONObject json = new JSONObject();
            json.put("url", url);
            json.put("callbackUrl", callbackUrl + "/social/sync-end/" + productId +"/" + SecurityUtils.getUserId());
            StringEntity entity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);

            httpPost.setHeader("Accept", "application/json");

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getCode();
                if (statusCode!=200) {
                    throw new I18nException("product.error.http");
                }
                String responseBody = EntityUtils.toString(response.getEntity());
                JSONObject responseBod = JSONObject.parseObject(responseBody);
                String taskId = responseBod.getString("taskId");
                String restype = responseBod.getString("type");
                System.out.println("taskId:"+taskId);
                System.out.println("restype:"+restype);
                return  restype;
            } catch (I18nException e) {
                throw e;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new I18nException("product.error.http");
        }
    }
}